<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ include file="loginDetails.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<HTML>
<BODY>

<%!
boolean validateLogin(JspWriter out,HttpServletRequest request,
					HttpSession session)
{
	String username = request.getParameter("username");
	String password = request.getParameter("password");
        
	String retStr = null;
	String hashedPassword = null;
	String salt = null;
	boolean isAdmin = false;
	int userId = -1;
	if(username == null || password == null)
		return false;
	if((username.length() == 0) || (password.length() == 0))
		return false;
	// Should make a database connection here and check password
	try { // Load driver class
		Class.forName("com.mysql.jdbc.Driver");
	}
	catch (java.lang.ClassNotFoundException e) {
		System.err.println("ClassNotFoundException: " +e);
	}
	Connection con = null;
	try { 
		con = DriverManager.getConnection(url+db, uid, pwd); 
		Statement stmt = con.createStatement();
		ResultSet rst = stmt.executeQuery("SELECT UserId, HashedPW, Salt, IsAdmin FROM User WHERE Username= '" + username + "'");

		while (rst.next()){ 
			hashedPassword = rst.getString("HashedPW");
			salt = rst.getString("Salt");
			userId = rst.getInt("UserId");
			isAdmin = rst.getBoolean("IsAdmin");
		}
		con.close();
	}
	catch (Exception ex) { 
		System.err.println(ex); 
	}
	finally{ 
		if (con != null)
		try
		{ con.close(); }
		catch (SQLException ex) { System.err.println(ex); }
	} 
        
        // There was no user found for the given username.
	if(userId < 0){
		session.setAttribute("loginMessage","Failed login.");
		return false;
	}
        
        // Checking to see if the password is correct
	else if(CheckPasswordCorrect(hashedPassword, salt, password)){ 	
		session.removeAttribute("loginMessage");
		session.setAttribute("Username",username);
		session.setAttribute("UserId",userId);
		session.setAttribute("IsAdmin", isAdmin);
		return true;
	}
	else
		session.setAttribute("loginMessage","Failed login.");
		return false;
} 
%>


<%
boolean authenticatedUser = false;
session = request.getSession(true);// May create new session
//try{
	authenticatedUser = validateLogin(out,request,session);
//}
//catch(IOException e){ System.err.println(e); }

if(!authenticatedUser)
	response.sendRedirect("index.jsp"); // Success
else
	response.sendRedirect("Home.jsp"); // Failed login
// Redirect back to login page with a message
%>

</BODY>
</HTML>